/**
 * Created by CDog on 15/9/1.
 */

wcApp.directive("ensureUnique",['$http', '$rootScope',function ($http,$rootScope) {
    return{
        require:'ngModel',
        link : function (scope, ele, attrs, c) {
            scope.$watch(attrs.ngModel,function(n){
                var con={};
                switch (attrs.ensureUnique){
                    case "mobile":
                        con={
                            lth:11,
                            name:"手机号"
                        };
                        break;
                    case "stdNumber":
                        con={
                            lth:9,
                            name:"学号"
                        };
                        break;
                }
                if (!n || n.length!=con.lth) return;
                scope.showTips("",true,1);
                $http.get($rootScope.baseUrl+"/users/isUnique/"+attrs.ensureUnique+"/"+n)
                    .success(function (data) {
                        if (data.code!=200){
                            c.$setValidity("unique",false);
                            scope.showTips("该"+con.name+"已被注册，请尝试<a href='#/login'>登陆</a>",true);
                        }else{
                            c.$setValidity("unique",true);
                        }
                    })
            })
        }
    }
}]);


wcApp.directive("hasUserMobile",['$http', '$rootScope',function ($http,$rootScope) {
    return{
        require:'ngModel',
        link : function (scope, ele, attrs, c) {
            scope.$watch(attrs.ngModel,function(n){
                var con={};
                con={
                    lth:11,
                    name:"手机号"
                };

                if (!n || n.length!=con.lth) return;
                scope.showTips("",true,1);
                $http.get($rootScope.baseUrl+"/users/hasUser/"+n)
                    .success(function (data) {
                        if (data.code==404){
                            c.$setValidity("unique",false);
                            scope.showTips("该"+con.name+"还未注册，请尝试<a href='#/verify'>注册认证</a>",true);
                        }else{
                            c.$setValidity("unique",true);
                        }
                    })
            })
        }
    }
}])